package sql.query;

import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import sql.parser.InsertSyntax;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ObjectInsert {
    private final ObjectVisitor objectVisitor;
    private InsertSyntax insertSyntax;

    public ObjectInsert(ObjectVisitor objectVisitor, InsertSyntax insertSyntax) {
        this.objectVisitor = objectVisitor;
        this.insertSyntax = insertSyntax;
    }

    public boolean save() {
        String table = insertSyntax.getTable();
        List<String> columns = insertSyntax.getColumns();
        List<List<String>> values = insertSyntax.getValues();

        if(StringUtils.isBlank(table)) {
            return false;
        }
        if(columns.isEmpty()) {
            return false;
        }
        if(values.isEmpty()) {
            return false;
        }

        List list = objectVisitor.readTable(table);
        for (List<String> valueItem : values) {
            Map map = new HashMap();
            for (int i = 0; i < columns.size(); i++) {
                String key = columns.get(i);
                String value = valueItem.get(i);
                ObjectDataType jsonDataType = ObjectDataType.getJsonDataType(value);
                switch (jsonDataType) {
                    case Long:
                        map.put(key, NumberUtils.toLong(value));
                        break;
                    case Double:
                        map.put(key, NumberUtils.toDouble(value));
                        break;
                    case Boolean:
                        map.put(key, BooleanUtils.toBoolean(value));
                        break;
                    default:
                        map.put(key, value);
                        break;
                }
            }
            list.add(map);
        }

        objectVisitor.writeTable(table, list);

        return true;
    }
}
